<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :forceRender="true"
    switchFullscreen
    @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{$t('inPrint.cancel')}}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleOk" :disabled="submitBtnDisabled">{{$t('commodityManagement.preservation')}}</a-button>
    </template>
    <div style="position:absolute;bottom:53px;right:0;z-index:11" v-if="showRecover && !model.id">
      <span>{{ $t('popup.recoveryPrompt') }}</span>
      <a-button type="link" @click="recover" :disabled="submitBtnDisabled">{{$t('popup.recover')}}</a-button>
      <a-button type="link" @click="lose" :disabled="submitBtnDisabled">{{$t('popup.lose')}}</a-button>
    </div>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <!-- 盘点仓库 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
              :label="$t('warehouseManagement.inventoryDepotName')">
              <a-select style="width: 200px" :placeholder="$t('warehouseManagement.pleaseSelectInventoryDepotName')" 
                v-decorator="['depotId', validatorRules.depotId]" @select="onSelectedWarehouse">
                  <a-select-opt-group>
                    <span slot="label">{{$t('inPrint.self')}}</span>
                    <a-select-option v-for="(item, index) in selfDepot" :key="index" :value="item.id">
                    {{ item.depotName || item.name }}
                  </a-select-option>
                  </a-select-opt-group>
                  <a-select-opt-group :label="$t('inPrint.other')">
                    <a-select-option v-for="(item, index) in othoerDepot" :key="index" :value="item.id">
                    {{ item.depotName || item.name }}
                  </a-select-option>
                  </a-select-opt-group>
                </a-select>
            </a-form-item>
          </a-col>

          <!-- 操作员 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')"
              data-step="3" :data-title="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator.trim="['userName']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')"
              data-step="2" :data-title="$t('setailManagement.documentNo')"
              :data-intro="$t('popup.theNumberIsGenerated')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="['custom5']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator.trim="['creator']" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['operTime', validatorRules.operTime]" :show-time="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="[ 'number' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="[ 'tenantId' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24"></a-col>
        </a-row>
        
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }" >
              <span>{{$t('popup.documentRemark')}}：</span>
              <a-textarea :rows="1" :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="['remark']"
                style="margin-top:8px;width: 88%;" />
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table id="billModal"
          :ref="refKeys[0]"
          :loading="materialTable.loading"
          :columns="materialTable.columns"
          :dataSource="materialTable.dataSource"
          :minWidth="minWidth"
          :maxHeight="300"
          :rowNumber="false"
          :rowSelection="true"
          :actionButton="true"
          :dragSort="true"
          @valueChange="barCodeValueChange" 
          @onBlurChange="onBlurChange"
          @added="onAdded"
          @deleted="onDeleted">
          <template #buttonAfter><a-row :gutter="24" style="float:left;padding-bottom: 5px;padding-right: 10px;">
              <a-col v-if="scanStatus" :md="6" :sm="24">
                <a-upload :disabled="!canImport"  name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
                  <a-popover :title="$t('commodityManagement.formTemplate')">
                    <template slot="content">
                      <p><a target="_blank" :href="`/doc/inventory_template${getLanCode() === 'en' ? '_en' :''}.xls`"><b>{{$t('commodityManagement.productDownload')}}</b></a></p>
                    </template>
                    <a-button :disabled="!canImport" type="primary" icon="import">{{$t('commodityManagement.import')}}</a-button>
                  </a-popover>
                </a-upload>
              </a-col>
            </a-row>
            <a-row :gutter="24" style="float:left;" data-step="4" :data-title="$t('popup.codeScanningEntry')" :data-intro="$t('popup.thisSupportsGun')">
              <a-col v-if="scanStatus" :md="6" :sm="24">
                <a-button @click="scanEnter">{{$t('popup.codeScanningEntry')}}</a-button>
              </a-col>
              <a-col v-if="!scanStatus" :md="16" :sm="24" style="padding: 0 6px 0 12px">
                <a-input :placeholder="$t('popup.pleaseScanBarcode')" v-model="scanBarCode" @pressEnter="scanPressEnter" ref="scanBarCode"/>
              </a-col>
              <a-col v-if="!scanStatus" :md="6" :sm="24" style="padding: 0px">
                <a-button @click="stopScan">{{$t('popup.stowScanningCode')}}</a-button>
              </a-col>
            </a-row>
            <a-row :gutter="24" style="float:left;">
              <a-col :md="24" :sm="24">
                <a-dropdown>
                  <a-menu slot="overlay">
                    <a-menu-item key="1" @click="handleBatchSetDepot"><a-icon type="setting"/>{{$t('popup.batchSettings')}}</a-menu-item>
                    <a-menu-item v-if="isTenant" key="2" @click="addDepot"><a-icon type="plus"/>{{$t('popup.newWarehouse')}}</a-menu-item>
                  </a-menu>
                  <a-button style="margin-left: 8px">{{$t('popup.warehouseOperation')}} <a-icon type="down" /></a-button>
                </a-dropdown>
              </a-col>
            </a-row>
          </template>
        </j-editable-table>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('popup.enclosure')">
              <div v-if="fileLoading">Loading...</div>
              <j-upload v-else :fileList="fileList" bizPath="bill"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <vendor-modal ref="vendorModalForm" @ok="vendorModalFormOk"></vendor-modal>
    <depot-modal ref="depotModalForm" @ok="depotModalFormOk"></depot-modal>
    <batch-set-depot ref="batchSetDepotModalForm" @ok="batchSetDepotModalFormOk"></batch-set-depot>
  </j-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import VendorModal from '../../system/modules/VendorModal'
  import DepotModal from '../../system/modules/DepotModal'
  import BatchSetDepot from '../dialog/BatchSetDepot'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { BillModalMixin } from '../mixins/BillModalMixin'
  import { getMpListShort } from "@/utils/util"
  import JUpload from '@/components/jeecg/JUpload'
  import JDate from '@/components/jeecg/JDate'
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import { findStockByMeIds } from "@/api/api"
  import { getAction } from '@/api/manage'
  import Vue from 'vue'
  import { isNumber } from 'lodash'
  import {getLanCode} from '@/lang';
  export default {
    name: "OtherInModal",
    mixins: [JEditableTableMixin, BillModalMixin],
    components: {
      VendorModal,
      DepotModal,
      BatchSetDepot,
      JUpload,
      JDate,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
    },
    
    provide(){
      return {
        getConfig: ()=>{
          return {depotId: this.depotId}
        }
      }
    },
    data () {
      return {
        title:this.$t('setailManagement.operation'),
        width: '1600px',
        moreStatus: false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        visible: false,
        operTimeStr: '',
        tokenHeader: { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) },
        prefixNo: 'PDDD',
        fileList:[],
        depotId:'',//当前仓库id
        model: {},
        selfDepot:[],
        canImport:false,
        othoerDepot:[],
        anotherDepotList:[],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        refKeys: ['materialDataTable', ],
        activeKey: 'materialDataTable',
        materialTable: {
          loading: false,
          dataSource: [],
          columns: [
            { title: this.$t('warehouseManagement.inventoryDepotName'), key: 'depotId', width: '7%', type: FormTypes.select,disabled:true, placeholder: this.$t('inPrint.pleaseTnter')+'${title}', options: [],
              allowSearch:true, validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            },
            { title: this.$t('reportQuery.barcode'), key: 'barCode', width: '8%', type: FormTypes.hidden, multi: true,
              // validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            },
            { title: this.$t('otherJS.goodsId'), key: 'meId', width: '9%', type: FormTypes.hidden },
            { title: this.$t('otherJS.goodsId'), key: 'materialId', width: '9%', type: FormTypes.hidden },
            { title: this.$t('reportQuery.name'), key: 'name', width: '18%', type: FormTypes.normal, kind: 'material', },
            { title: this.$t('reportQuery.specification'), key: 'standard', width: '14%', type: FormTypes.normal },
            { title: this.$t('reportQuery.category'), key: 'categoryName', width: '6%', type: FormTypes.input,readonly:true  },
            { title: this.$t('reportQuery.model'), key: 'model', width: '5%', type: FormTypes.normal },
            // { title: this.$t('reportQuery.extendedInformation'), key: 'materialOther', width: '5%', type: FormTypes.hidden },
            { title: this.$t('reportQuery.inventory'), key: 'stock', width: '5%', type: FormTypes.input,disabled:true },
            { title: this.$t('reportQuery.unit'), key: 'unit', width: '6%', type: FormTypes.normal },
            
            { title: this.$t('warehouseManagement.inventoryNumber'), key: 'operNumber1', width: '5%', type: FormTypes.inputNumber, statistics: true,
              validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            },
            { title: this.$t('warehouseManagement.costUnitPrice'), key: 'purchaseDecimal', width: '5%', type: FormTypes.inputNumber},
            { title: this.$t('warehouseManagement.breakNumber'), key: 'differNumber', width: '5%', type: FormTypes.input, statistics: true,disabled:true },
            { title: this.$t('financialManagement.remarks'), key: 'remark', width: '5%', type: FormTypes.input },
             
          ]
        },
        confirmLoading: false,
        validatorRules:{
          operTime:{
            rules: [
              { required: true, message: this.$t('popup.pleaseEnterDocumentDate')+'!' }
            ]
          },
          type:{
            rules: [
              { required: true, message: this.$t('basicInformation.pleaseType')+'!' }
            ]
          },
          number:{
            rules: [
              { required: true, message: this.$t('otherJS.DocumentNoFailure') }
            ]
          }
        },
        url: {
          add: '/depotHead/addDepotHeadAndDetail',
          edit: '/depotHead/updateDepotHeadAndDetail',
          importExcelUrl: "/material/importOpeningInventory",
          detailList: '/depotItem/getDetailList'
        }
      }
    },
    methods: {
      getLanCode,
      onSelectedWarehouse (value) {
        this.materialTable.columns[4].type = FormTypes.popupJsh
        this.canImport = true
        const table = this.$refs[this.refKeys[0]]
        const depot = this.anotherDepotList.find(v=>v.id === value)
        let tenantId = ''
        if(depot && depot.id){
          tenantId = depot.tenantId
        }
        table.getValues((err, values) => {
          const array = values.map(item => {
            return {
              rowKey: item.id,
              values: {
                depotId: value
              }
            }
          })
        this.depotSelectChange(value)
        this.$nextTick(() => {
            table.setValues(array)
            this.form.setFieldsValue({'tenantId':tenantId})
            if(this.materialIds){
              this.confirmLoading = true;
              this.submitBtnDisabled = true;
              this.getMaterialInfo(value).then(res=>{
                if(res.data && res.data.length){
                  const arr = res.data.map(item => {
                    return {
                      rowKey: item.id,
                      values: {
                        stock: item.stock,
                        differNumber: this.$toDecimal(item.operNumber1 - item.stock)
                      }
                    }
                  })
                  
                table.setValues(arr)
                this.confirmLoading = false;
                this.submitBtnDisabled = false;
                }
              })
            }
          })
        }, false)
      },
      
      onAdded (event) {
        const { row, target } = event
        const depotId  = this.form.getFieldValue('depotId')
        target.setValues([{ rowKey: row.id, values: { operNumber: 0,depotId:depotId } }])
        // 聚焦新增的行
        this.$nextTick(()=>{
          const input = document.querySelectorAll(`#name${target.caseId+row.id + target.tempId} input`)
          setTimeout(()=>{
            input && input.length && (input[0].value = '')
          },200);
          input && input.length && input[0].focus()
          target.setValues([{ rowKey: row.id, values: { name: ''} }])
        })
        
      },
      depotChange(e){
        this.depotId = e
        this.materialTable.columns[4].type = FormTypes.popupJsh
        this.depotSelectChange(e)
       if(!this.materialTable.dataSource.length) return;
        this.$refs.materialDataTable.getValues((err,values)=>{
          let arr = values
          arr.forEach(val=>{
            this.$set(val,'depotId',e)
          })
          this.$nextTick(()=>{
            this.materialTable.dataSource = arr
          })
        })
      },
      
      depotSelectChange(e){
        let item = this.anotherDepotList.find(v=>v.id === e)
        this.$nextTick(()=>{
            this.form.setFieldsValue({
              'custom5':item && item.tenantId
            })
        })
      },
    
      importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }, 
    /**
     * 获取所有用户的仓库
     */
    getAnotherDepotData() {
      getAction('/depot/findDepotList').then(res => {
        if (res.code === 200) {
          this.anotherDepotList = res.data
          let creator = this.getLocalStorage('pro__Login_Userinfo').tenantId
          this.selfDepot = this.anotherDepotList.filter(v=>v.tenantId === creator)
          this.othoerDepot = this.anotherDepotList.filter(v=>v.tenantId !== creator)
          // 表体
          let arr = res.data
          for (let item of this.materialTable.columns) {
            if (item.key == 'depotId' || item.key == 'anotherDepotId') {
              item.options = []
              for (let i = 0; i < arr.length; i++) {
                let depotInfo = {}
                depotInfo.value = arr[i].id + '' //注意-此处value必须为字符串格式
                depotInfo.text = arr[i].name
                depotInfo.title = arr[i].name
                depotInfo.depotName = '仓库'
                item.options.push(depotInfo)
              }
            }
          }
        } else {
          this.$message.info(res.data)
        }
      })
    },
    
    /* 导入 */
    async handleImportExcel(info) {
      this.loading = true
      this.confirmLoading = true
      this.submitBtnDisabled = true
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 200) {
            let dataSource = info.file.response.data
            dataSource.forEach(item => {
              item.unitPrice = item.billPrice
              item.unit = item.commodityUnit
              item.depotId = this.form.getFieldValue('depotId') || '',
              item.operNumber1 = item.operNumber
            })
            this.materialTable.dataSource = dataSource
            const depotId = this.form.getFieldValue('depotId') || ''
            const table = this.$refs[this.refKeys[0]]
            if(depotId){
              const ids = dataSource.map(v=>v.id)
              const idsCount = Math.ceil(ids.length / 100)
              console.log('idsCount :>> ', idsCount);
              for (let index = 0; index < idsCount; index++) {
                let param = {
                      mId: ids.slice(index *100,(index+1)*100).join(','),
                      depotId: depotId,
                }
                findStockByMeIds(param).then(res => {
                    if(res.code == 200){
                      let stockArr = res.data
                      if(stockArr && stockArr.length){
                        dataSource.forEach(item => {
                          const info = stockArr.find(v=>v.id === item.id)
                          const stock = info && info.stock || 0
                          item.stock = stock 
                          item.differNumber = this.$toDecimal(item.operNumber1 - stock)
                        })
                        
                        const arr = res.data.map(item => {
                          const mInfo = dataSource.find(v=>v.id === item.id)
                          return {
                            rowKey: item.id,
                            values: {
                              stock: item.stock || 0,
                              depotId:depotId,
                              differNumber: this.$toDecimal(mInfo.operNumber1 - (item.stock||0))
                            }
                          }
                        })
                        this.$nextTick(()=>{
                          table.setValues(arr)
                          if((index + 1) * 100 >= ids.length ){
                            this.confirmLoading = false
                            this.submitBtnDisabled = false
                            this.loading = true
                          }
                        })
                      }
                    }else{
                      this.$message.error(res.message || res.data || res.data.message)
                    }
                  })
              }
            }
            this.changeMaterialIds()
            this.$message.success(info.file.name + this.$t('otherJS.uploadSuccess'))
          } else {
            this.$message.warning(info.file.response.data.message)
          }
          // this.loadData()
          if(!this.submitBtnDisabled){
            this.confirmLoading = false
            this.loading = false
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.data}.`)
          if(!this.submitBtnDisabled){
            this.confirmLoading = false
            this.loading = false
          }
        }
      } else if (info.file.status === 'error' && !this.submitBtnDisabled) {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
        this.loading = false
        this.confirmLoading = false
      }
    },
      //调用完edit()方法之后会自动调用此方法
      editAfter() {
        this.arrList = []
        this.billStatus = '0'
        if (this.action === 'add') {
          this.addInit(this.prefixNo)
          this.fileList = []
        this.materialTable.columns[4].type = FormTypes.normal
        this.canImport = false
        } else {
          this.model.operTime = this.model.operTimeStr
          
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'organId', 'operTime', 'number', 'remark','creator','userName',
              'discount','discountMoney','discountLastMoney','otherMoney','accountId','changeAmount'))
          });
          // 加载子表数据
          let params = {
            headerId: this.model.id,
            mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
          }
          let url = this.readOnly ? this.url.detailList : this.url.detailList;
          this.requestSubTableData(url, params, this.materialTable);
          let arr = []
          this.materialTable.dataSource.forEach(item => {
            arr.push(item.materialId)
          });
          this.materialIds = arr.toString()
          this.changeMaterialIds()
        }
        //复制新增单据-初始化单号和日期
        if(this.action === 'copyAdd') {
          this.model.id = ''
          this.model.tenantId = ''
          this.copyAddInit(this.prefixNo)
        }
        this.initWarehouseList();
        this.initSupplier()
        this.getAnotherDepotData()
      },
      
      onBlurChange(event) {
        console.log('row :>> ', event);
      const { type, row, column, value, target,index } = event
      this.submitBtnDisabled = true;
      switch (column.key) {
        case 'operNumber1':
        row.operNumber1 = value
        row.differNumber = +row.operNumber1 - row.stock
        target.setValues([{ rowKey: row.id, values: { operNumber1: value,differNumber:row.differNumber } }])
        break;
      }
      this.submitBtnDisabled = false;
    },
      //提交单据时整理成formData
      classifyIntoFormData(allValues) {
        let totalPrice = 0
        let billMain = Object.assign(this.model, allValues.formValue)
        let detailArr = allValues.tablesValue[0].values
        billMain.type = '其它'
        billMain.subType = '盘点单'
        billMain.defaultNumber = billMain.number
        for(let item of detailArr){
          totalPrice += item.allPrice-0
          item.custom12 = +item.differNumber ? 0 : 1
          item.operNumber = item.operNumber1
          item.unitPrice = item.purchaseDecimal
          item.depotId = this.form.getFieldValue('depotId')
          item.tenantId = this.form.getFieldValue('tenantId')
        }
        billMain.totalPrice = 0-totalPrice
        // if(this.fileList && this.fileList.length > 0) {
        //   billMain.fileName = this.fileList
        // } else {
        //   billMain.fileName = ''
        // }
        if(this.model.id){
          billMain.id = this.model.id
        }
        billMain.status = this.billStatus
        let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
        // console.log('billMain :>> ', billMain);
        // return;
        return {
          info: JSON.stringify(billMain),
          attachment: fileList,
          rows: JSON.stringify(detailArr),
        }
      },
      
    }
  }
</script>
<style scoped>

</style>